﻿using System;
using System.Reflection;
using System.Security;
using log4net;

/*
 *  author: able
 *  @2012/2/21 15:27:32
 * 
 */
namespace __ts.Core.Service
{
    /// <summary>
    /// 
    /// </summary>
    public class SelectorFactory
    {
        static ILog LOG = LogManager.GetLogger(typeof(SelectorFactory));

        private ConstructorInfo constructor;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="selectorClass"></param>
        public SelectorFactory(Type selectorClass)
        {
            try
            {
                constructor = selectorClass.GetConstructor(new Type[] { typeof(string), typeof(SelectorStrategy) });
            }
            catch (Exception e)
            {
                LOG.Error("Exception while instantiating selector", e);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="strategy"></param>
        /// <returns></returns>
        public SelectorProcessor getNewSelector(String name, SelectorStrategy strategy)
        {
            try
            {
                return (SelectorProcessor)constructor.Invoke(new object[] { name, strategy });
            }
            catch (SecurityException e)
            {
                LOG.Error("SecurityException while instantiating selector", e);
            }
            catch (ArgumentException e)
            {
                LOG.Error("ArgumentException while instantiating selector", e);
            }
            catch (TypeInitializationException e)
            {
                LOG.Error("TypeInitializationException while instantiating selector", e);
            }
            catch (AccessViolationException e)
            {
                LOG.Error("AccessViolationException while instantiating selector", e);
            }
            return null;
        }
    }
}